<script setup lang='ts'>


const props = defineProps({
  options: {
    type: Array as PropType<Option[]>,
    required: true,
  },
  hasTimeRange: {
    type: Boolean as PropType<boolean>,
    default: false,
  },
  hasTerminal: {
    type: Boolean as PropType<boolean>,
    default: false,
  },
  disabled: {
    type: Boolean as PropType<boolean>,
    default: false,
  },
  needReset: {
    type: Boolean as PropType<boolean>,
    default: true,
  },
})
const emit = defineEmits(['search'])
const timeRange = ref([])

const conds = defineModel({ default: [] })
const { options } = toRefs(props)

/* 终端搜索 */
const clientIdList = ref([])
const clientList = ref([])

watch([options, timeRange, clientIdList], ([val]) => {
  /** 找出给定的固有条件 */
  // const wayNames = val.map(item => item.ways.map(({ name }) => name)).flat()
  // const preConds = conds.value.filter(({ name }) => !wayNames.includes(name)).map(item => toRaw(item))
  const conditions = val.filter(({ model }) => !!model.value?.trim()).map((item) => {
    const model = item.model
    if (model.op === 'like')
      return { ...model, value: `%${model.value}%` }
    else
      return toRaw(model)
  })
  // .concat(preConds)

  if (props.hasTimeRange && timeRange.value.length === 2) {
    const timeConds = [
      {
        name: 'time_start',
        op: '>=',
        value: timeRange.value[0],
      },
      {
        name: 'time_start',
        op: '<=',
        value: timeRange.value[1],
      },
    ]
    conditions.push(...timeConds)
  }

  /* 终端 */
  if (props.hasTerminal && clientIdList.value.length) {
    conditions.push({
      name: 'client_id',
      op: 'in',
      value: clientIdList.value.join(','),
    })
  }
  conds.value = conditions
}, { deep: true })

async function queryClient(query) {
  const qobj = {
    limit: 200,
    start: 0,
    conditions: [],
  }
  if (query) {
    qobj.conditions.push({
      name: 'employee.name',
      op: 'like',
      value: `%${query}%`,
    })
  }
  const { inventories = [] } = await useRequest('QueryClient', qobj)
  clientList.value = inventories
}
const timeRangeRef = ref()
function reset() {
  options.value.forEach((option) => {
    option.model.value = ''
  })
  if (props.hasTerminal) {
    clientIdList.value = []
    clientList.value = []
  }
  if (props.hasTimeRange)
    timeRangeRef.value.reset()

  nextTick(() => emit('search'))
}

function searchDone() {
  timeRangeRef.value?.getRange()
  emit('search')
}
</script>

<template>
  <div class="flex-y-center space-x-3">
    <SearchItem v-for="(item, index) in options" :key="index" v-model="item.model" :ways="item.ways" />
    <slot name="extra" />
    <!-- 终端 -->
    <div v-if="props.hasTerminal" class="flex-center">
      <span class="label">终端</span>
      <el-select
        v-model="clientIdList"
        class="!w-50"

        clearable filterable remote multiple
        placeholder="请输入账号搜索，可多选"
        :remote-method="queryClient"
      >
        <el-option
          v-for="item in clientList"
          :key="item.uuid"
          :label="`${item.employeeName}(系统：${item.os})`"
          :value="item.uuid"
        />
      </el-select>
    </div>
    <TimeRange v-if="hasTimeRange" ref="timeRangeRef" v-model="timeRange" :show-button="false" isms />
    <el-button type="primary" class="no-border" :disabled="disabled" @click="searchDone">
      搜索
    </el-button>
    <el-button v-if="needReset" type="warning" class="no-border" @click="reset">
      重置
    </el-button>
  </div>
</template>

<style scoped lang='scss'>
  .label {
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  height: 28px;
  line-height: 26px;
  color: #666;
  font-size: 12px;
  padding: 0 8px;
  background: #f5f7fa;
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
  white-space: nowrap;
  transform: translate(1px, 0);
}
.el-select :deep(.el-select__wrapper) {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}
</style>
